<template>
  <div>
    <I-Input
      v-model="fieldValue"
      is-link
      readonly
      :required="required"
      :rules="rules"
      :label="label"
      :input-align="inputAlign"
      :placeholder="placeholder"
      @click="showPickerClick"
    ></I-Input>
    <van-popup v-model:show="showPicker" round position="bottom">
      <van-date-picker
        :title="title"
        :min-date="minDate"
        :max-date="maxDate"
        :model-value="dateArray"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup name="IDatePicker">
import { ref, watch, computed } from 'vue'
import dayjs from 'dayjs'

const emit = defineEmits(['update:modelValue', 'change'])

const props = defineProps({
  label: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: '选择日期'
  },
  required: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: String,
    required: true
  },
  rules: {
    type: Array,
    default: () => []
  },
  inputAlign: {
    type: String,
    default: 'right'
  },
  placeholder: {
    type: String,
    default: '请选择日期'
  },
  format: {
    type: String,
    default: 'YYYY-MM-DD'
  },
  minDate: {
    type: Date,
    default: () => new Date(2000, 0, 1)
  },
  maxDate: {
    type: Date,
    default: () => new Date(2100, 11, 31)
  }
})

const fieldValue = ref('')
const showPicker = ref(false)
const currentDate = ref(new Date())

// 计算日期数组 [年, 月, 日]
const dateArray = computed(() => {
  const date = currentDate.value
  return [date.getFullYear(), date.getMonth() + 1, date.getDate()]
})

// 初始化和监听值变化
watch(
  () => props.modelValue,
  (value) => {
    if (!value) {
      fieldValue.value = ''
      currentDate.value = new Date()
      return
    }

    const date = dayjs(value)
    if (date.isValid()) {
      currentDate.value = date.toDate()
      fieldValue.value = date.format(props.format)
    }
  },
  { immediate: true }
)

const showPickerClick = () => {
  showPicker.value = true
}

const onConfirm = ({ selectedValues }) => {
  showPicker.value = false
  // selectedValues 是一个数组 [年, 月, 日]
  const date = new Date(selectedValues[0], selectedValues[1] - 1, selectedValues[2])
  const formattedDate = dayjs(date).format(props.format)
  fieldValue.value = formattedDate
  currentDate.value = date
  emit('update:modelValue', formattedDate)
  emit('change', date)
}
</script>

<style scoped>
</style> 